const express = require('express');
const puppeteer = require('puppeteer');
const bodyParser = require('body-parser');

const ffmpeg = require('fluent-ffmpeg');
const fs = require('fs');
const path = require('path');
const aliOss = require('./utils/aliOss');
const app = express();
app.use(bodyParser.json());

let imgArrayBufferData = [];
const upLoadVideo = async (picPath) => {
    console.log('上传');
    let res = await aliOss(`${picPath}/p4.mp4`, (p, client) => {
        onProgress(p);
    });
    const onProgress = (p) => {
        console.log(Math.floor(p * 100));
    };
    console.log('结果');
    console.log(res);
    return res;
};

app.post('/generate-echarts', async (req, res) => {
    const { templateName, baseMsg } = req.body;
    console.error('请求参数:', baseMsg);
    if (!templateName) {
        return res.status(400).send('缺少模板名称');
    }

    if (!baseMsg) {
        return res.status(400).send('缺少ECharts配置参数');
    }

    const templatePath = path.join(__dirname, './echarts.html');

    if (!fs.existsSync(templatePath)) {
        return res.status(404).send('模板文件不存在');
    }
    const randoms = Math.floor(Math.random() * (100 - 1)) + 1;
    console.log(randoms);
    // 临时图片文件目录
    let tempDir = './temp' + randoms + Date.now();
    console.log(tempDir);
    let picPath = path.join(__dirname, tempDir);
    let browser;
    try {
        // 启动无头浏览器
        browser = await puppeteer.launch({ headless: 'new' });
        const page = await browser.newPage();
        imgArrayBufferData = [];
        // 访问一个网址
        await page.goto(templatePath);

        // 等待 #chart 元素加载完成
        await page.waitForSelector('#main', { timeout: 60000 });

        // 将配置参数传递给页面并渲染图表
        await page.evaluate((baseMsg) => {
            window.postMessage(baseMsg, '*');
        }, baseMsg);

        // 等待 ECharts 动画完成
        await page.waitForFunction(() => window.isFinishedBz === true, { timeout: 60000 });

        //假设你想获取一个全局变量 `myVariable` 的值
        imgArrayBufferData = await page.evaluate(() => {
            console.log('获取列表');
            return window.myVariable; // 替换为你的变量名
        });
        await ffTOVideo(tempDir);
        let isOk = await picToVideo(baseMsg, picPath);
        console.log('isOk', isOk);

        //这里进行
        let { url } = await upLoadVideo(picPath);
        // res.setHeader('Content-Type', 'image/png');
        res.send(url);
        //最后删除临时文件夹
        await rmdirHandle(tempDir);
    } catch (error) {
        console.error('生成图表时出错:', error);
        res.status(500).send('生成图表时出错');
    } finally {
        if (browser) {
            await browser.close();
        }
    }
});
async function ffTOVideo(tempDir) {
    // 创建临时目录
    if (!fs.existsSync(tempDir)) {
        fs.mkdirSync(tempDir);
    }

    // 将 Base64 图片解码并保存为临时文件
    imgArrayBufferData.forEach(async (base64Image, index) => {
        const matches = base64Image.match(/^data:image\/([a-zA-Z]+);base64,(.+)$/);
        if (matches) {
            const ext = matches[1];
            const data = matches[2];
            const buffer = Buffer.from(data, 'base64');
            const filePath = path.join(tempDir, `${index}.${ext}`);
            fs.writeFileSync(filePath, buffer);
        }
    });
}
async function picToVideo(baseMsg, picPath) {
    // 图片文件路径数组
    return new Promise(async (resolve, reject) => {
        const imageFiles = `${picPath}/%d.png`;
        console.log(imageFiles);
        // 创建一个新的 ffmpeg 命令
        const command = ffmpeg();
        command
            .addInput(imageFiles)
            .autopad(true, 'white')
            .inputOptions('-framerate 20') // 设置输入帧率，每秒1帧
            .outputOptions([`-vf scale=${baseMsg.width}:-2`, '-pix_fmt yuv420p'])
            .on('start', function (commandLine) {
                console.log('Spawned FFmpeg with command: ' + commandLine);
            })
            .on('error', function (err, stdout, stderr) {
                console.error('Error:', err);
                console.error('ffmpeg stderr:', stderr);
            })
            .on('end', async function (stdout, stderr) {
                console.log('Transcoding succeeded !');
                resolve(true);
            })
            .save(`${picPath}/p4.mp4`);
    });
}
async function rmdirHandle(tempDir) {
    console.log('删除临时图片文件');
    // 删除临时图片文件
    fs.rm(tempDir, { recursive: true, force: true }, (err) => {
        if (err) {
            console.error(`Error while deleting ${tempDir}.`, err);
        } else {
            console.log(`${tempDir} is deleted!`);
        }
    });
}

const PORT = 9000;
app.listen(PORT, () => {
    console.log(`Puppeteer 服务运行在端口 ${PORT}`);
});
